package v3.chapter2.t9;

import java.util.ArrayList;
import java.util.List;

public class Run {

	public static void main(String[] args) throws InterruptedException {
		MyOneList service = new MyOneList();
		MyThread1 a = new MyThread1(service);
		a.setName("A");
		a.start();

		MyThread2 b = new MyThread2(service);
		b.setName("B");
		b.start();
		Thread.sleep(6000);
		System.out.println("listSize=" + service.getSize());
	}

}

class MyThread1 extends Thread {

	private MyOneList service;

	public MyThread1(MyOneList service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		MyService msRef = new MyService();
		msRef.addServiceMethod(service, "A");
	}
}

class MyThread2 extends Thread {

	private MyOneList service;

	public MyThread2(MyOneList service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		MyService msRef = new MyService();
		msRef.addServiceMethod(service, "B");
	}
}

class MyService {
	public MyOneList addServiceMethod(MyOneList list, String data) {
		try {
			// 解决 “脏读”
			//synchronized (list) {
				if (list.getSize() < 1) {
					Thread.sleep(2000);
					list.add(data);
				}
			//}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return list;
	}
}

class MyOneList {
	private List list = new ArrayList();

	synchronized public void add(String data) {
		list.add(data);
	}

	synchronized public int getSize() {
		return list.size();
	}
}